var glob = require('glob')
var path = require('path')
var fs = require('fs')

var changeFileMap = {}
var unFanyiList = []
var fanyiList = []
var fileList = glob.sync('./src/?(pages|components)/**/*.vue')

fileList.forEach(function (file) {
  // console.log('111', path.resolve(file))
  const content = fs.readFileSync(file, 'utf-8')

  // console.log('content', content)

  const {
    hasReplace: i18nHasReplace,
    content: i18nContent,
    fanyiList: i18nFanyiList,
    unFanyiList: i18nUnFanyiList
  } = replaceI18n(content)

  fanyiList = [...fanyiList, ...i18nFanyiList]
  unFanyiList = [...unFanyiList, ...i18nUnFanyiList]

  if (i18nHasReplace) {
    changeFileMap[file] = i18nContent
  }
})

Object.keys(changeFileMap).forEach((file) => {
  fs.writeFileSync(file, changeFileMap[file])
})

console.log('本次共扫码', fileList.length, '个文件')
console.log('处理', Object.keys(changeFileMap).length, '个文件')
console.log('已翻译', fanyiList.length)
console.log('未翻译', unFanyiList.length)

// TODO: 对接翻译

function replaceI18n(content) {
  let hasReplace = false
  let fanyiList = []
  let unFanyiList = []
  content = content.replace(/<template(.|\n|\r)*template>/gim, (match) => {
    // 处理 :attr="``"
    return match
      .replace(/(["'])`([^`\n\r]*[\u4e00-\u9fa5]+[^`\n\r]*)`(\1)/gim, (_, prev, match, after) => {
        match = match.trim()
        unFanyiList.push(match)
        hasReplace = true
        return prev === '"' ? `"$t('${match}')"` : `'$t("${match}")'`
      })
      .replace(
        /(\$t\()?(\w+='|\w+="|>|'|")([^'"<>{]*[\u4e00-\u9fa5]+[^'"<>{]*)(['"<{])/gim,
        (_, t, prev, match, after) => {
          if (t) {
            fanyiList.push(match)
            return _
          }
          match = match.trim()
          hasReplace = true
          if (match.match(/{{([^{}]+)}}/)) {
            unFanyiList.push(RegExp.$1.trim())
            return `${prev}{{ $t('${RegExp.$1.trim()}') }}${after}`
          }

          unFanyiList.push(match)

          if (prev.match(/^\w+='$/)) {
            //对于属性中普通文本的替换
            return `:${prev}$t("${match}")${after}`
          }

          if (prev.match(/^\w+="$/)) {
            //对于属性中普通文本的替换
            return `:${prev}$t('${match}')${after}`
          }

          if (prev === '"' || prev === "'") {
            //对于属性中参数形式中的替换
            return `$t(${prev}${match}${after})`
          }

          //对于tag标签中的普通文本替换
          return `${prev}{{$t('${match}')}}${after}`
        }
      )
  })

  return {
    hasReplace,
    content,
    fanyiList,
    unFanyiList,
  }
}
